package com.hornet.oauth.web.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hornet.commons.web.BaseController;
import com.hornet.commons.web.model.AjaxResponse;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;

@Controller
@RequestMapping("/oauth/qq")
public class QQLoginController extends BaseController {

	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse sina_weibo_login(HttpServletRequest request, HttpSession session) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		try {
			System.out.println("使用QQ登录....");

			response.setContentType("text/html;charset=utf-8");
			String redirect_url = new Oauth().getAuthorizeURL(request);
			ajaxResponse.setMessage(redirect_url);
			System.out.println(redirect_url);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ajaxResponse;
	}
	
	@RequestMapping(value = "callback", method = RequestMethod.GET)
	public String weibo_callback(@RequestParam String code) {
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = this.response.getWriter();
			
			AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);

			String accessToken = null;
			String openID = null;
			long tokenExpireIn = 0L;
			
			if (accessTokenObj.getAccessToken().equals("")) {
				// 我们的网站被CSRF攻击了或者用户取消了授权
				// 做一些数据统计工作
				System.out.print("没有获取到响应参数");
			} else {
				accessToken = accessTokenObj.getAccessToken();
				tokenExpireIn = accessTokenObj.getExpireIn();

				request.getSession().setAttribute("demo_access_token", accessToken);
				request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));

				// 利用获取到的accessToken 去获取当前用的openid -------- start
				OpenID openIDObj = new OpenID(accessToken);
				openID = openIDObj.getUserOpenID();

				out.println("欢迎你，代号为 " + openID + " 的用户!");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/oauth/qq_callback" ;
	}
}
